package com.ting.template.core.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

/**
 * <p>文件操作工具类</p>
 * @author Your name
 * @version $Id: PropertyUtil.java, v 0.1 2017年6月29日 上午10:08:53 雷霆 Exp $
 */
public class PropertyUtil {
	private static final Logger logger = LoggerFactory.getLogger(PropertyUtil.class);
	private String location;
	private static PropertyUtil instance;
	private static ResourceLoader resourceLoader;
	private static Properties properties;

	public PropertyUtil(String location) {
		this.location = location;
		this.init();
	}

	public static PropertyUtil getInstance(String location) {
		if (instance == null) {
			instance = new PropertyUtil(location);
		}
		return instance;
	}

	private void init() {
		InputStream is = null;
		try {
			Resource resource = resourceLoader.getResource(location);
			is = resource.getInputStream();
			properties.load(is);
		} catch (IOException ex) {
			logger.error("文件读取出现异常: {}", ex.getMessage());
			// ex.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException ex1) {
				logger.error("关闭文件流出现异常: {}", ex1.getMessage());
				// ex1.printStackTrace();
			}
		}
	}

	public String getValue(String key) {
		String systemProperty = System.getProperty(key);
		if (systemProperty != null) {
			return systemProperty;
		}
		return properties.getProperty(key);
	}

	public static void main(String[] args) {
		String location = "test.properties";
		PropertyUtil util = PropertyUtil.getInstance(location);
		System.out.println(util.getValue("test"));
	}

}
